﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;

namespace SPThumbnailExtender.Interne
{
    internal delegate void CodeToRunAppPool();
    internal class RevertToAppPool
    {
        private WindowsImpersonationContext ctx = null;

        //Revert to the original application pool security context
        //We only want to do this if we are not already running as the system
        public void UseAppPoolIdentity()
        {
            try
            {
                if (!WindowsIdentity.GetCurrent().IsSystem)
                {
                    ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
                }
            }
            catch { }
        }

        //Return to impersonating the authenticated user
        //Anonymous users are impersonated as IUSR_machinename, by default
        public void ReturnToImpersonatingCurrentUser()
        {
            try
            {
                if (ctx != null)
                {
                    ctx.Undo();
                }
            }
            catch { }
        }
        public static void UseAppPoolIdentify(CodeToRunAppPool codetoRun)
        {
            RevertToAppPool rtap = new RevertToAppPool();
            rtap.UseAppPoolIdentity();
            codetoRun();
            rtap.ReturnToImpersonatingCurrentUser();
        }

    }
}
